import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import login from '@/views/login.vue'
import { ElMessageBox } from 'element-plus'
import Cookies from "js-cookie";
const routes = [{
        path: '/',
        redirect: '/home'
    },
    {
        path: '/home',
        name: 'home',
        component: HomeView,
        meta: {
            requireAuth: true //需要验证登录状态
        },
    },
    {
        path: '/login',
        name: 'login',
        component: login,
    },
    {
        path: '/about',
        name: 'about',
        // route level code-splitting
        // this generates a separate chunk (about.[hash].js) for this route
        // which is lazy-loaded when the route is visited.
        component: function() {
            return import ( /* webpackChunkName: "about" */ '../views/AboutView.vue')
        }
    }

]

const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
    // 判断该路由是否需要登录权限
    if (to.meta.requireAuth) {
        if (Cookies.get('satoken')) {
            next()
        } else {
            ElMessageBox.alert('您还未登录，是否前往登录页面？', '提示', {
                confirmButtonText: '确定',
                type: 'warning'
            }).then(() => {
                next({
                    path: '/login',
                    query: { redirect: to.fullPath }
                })
            }).catch(() => {})
        }
    } else {
        next()
    }
})


export default router